//
//  MJTTabBar.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/9.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit
//定义代理协议
protocol MJTTabBarDelegate: NSObjectProtocol {
    func didSelectedComposeButton()
}
class MJTTabBar: UITabBar {
    //点击撰写按钮的执行闭包
    var compeseBttonClosure: (() -> ())?
    //不能用delegate,系统已经有不能重名
    weak var MJTDelegate:MJTTabBarDelegate?
    //懒加载button
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside)
//        设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //自适应图片大小
        button.sizeToFit()
        return button
    }()
    //重写init,重新布局UI
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //添加加号视图
    private func setUpUI() {
        addSubview(composeButton)
    }
    //重新设置子控件的位置
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置按钮的中心
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
//        composeButton.center.x = frame.size.width * 0.5
//        composeButton.center.y = frame.size.height * 0.5
        //重新设置子控件布局
        //设置按钮宽度
        let itemWidth = width / 5
        //遍历子控件
        var index = 0
        //调整位置
        for value in subviews {
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                value.width = itemWidth
                value.x = CGFloat(index) * itemWidth
                index++
                if index == 2 {
                    index++
                }
            }
        }
    }
    func composeButtonAction() {
//        print("hh")
        //执行闭包
        compeseBttonClosure!()
        //调用代理
        MJTDelegate?.didSelectedComposeButton()
    }
}
